<template>
  <div>
    <!-- 基本信息 -->
    <jn-prj-detail :prj-id="prjId" />
    <!-- 站址信息 -->
    <jn-site-detail v-if="[14].includes(prjDetail.pageType)" :prj-id="prjId" />
    <!-- 专享信息 -->
    <jn-proprietary-detail :prj-id="prjId" :secondary-type="prjDetail.pageType" />
    <!-- 验收信息  -->
    <prj-accept-info v-if="isPrjAcceptInfo" ref="prjAcceptInfo" :prj-detail="prjDetail" />
    <!-- 附件  -->
    <zr-attachmetl prj-stage="F" :prj-id="prjId" />
    <!-- 审批  -->
    <jn-task-detail :process-inst-id="processInstId" />
    <t-page-btn v-if="type === 'todo' && btnList.length > 0" :btn-list="btnList" @handleBtn="handleBtn" />
    <next-page
      v-if="nextDialog.nextPageVisible"
      ref="nextPage"
      :visible.sync="nextDialog.nextPageVisible"
      :activity-inst-id="nextDialog.activityInstID"
      :process-inst-id="nextDialog.processInstID"
      :activity-def-id="nextDialog.activityDefID"
      :process-def-name="nextDialog.processDefName"
      :route="'1'"
      @doNextEntity="nextPageRes"
    />
    <Back-page
      v-if="backDialog.backPageVisible"
      ref="backPage"
      :visible.sync="backDialog.backPageVisible"
      :process-inst-id="nextDialog.processInstID"
      :act-inset-id="nextDialog.activityInstID"
      :route="backDialog.backRoute"
      @doReturn="backPageRes"
    />
    <el-dialog title="提示" :visible.sync="affirm.dialogVisible" width="30%">
      <span>{{ affirm.message }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="affirm.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAffirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="affirm.dialogVisible1" width="30%">
      <span>请确认是否还有未申领的物资与未验工计价的服务?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAffirm">否</el-button>
        <el-button type="primary" @click="affirm.dialogVisible1 = false">是</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  nonSelfResearchAcceptance
} from '@/api/electSingnare/index'
import {
  updateItAcceptTime,
  getPrjDetailApi,
  getWFWorkItemApi,
  itAcceptDoNextVerificationApi,
  projectVisaVerificationApi,
  getNotPushedDetailCodeApi,
  inspectionValuationPushApi,
  doNextFLowApi,
  checkMaterialServiceAmountApi,
  backActivityApi, checkCommonVerificationApi
} from '@/api/acceptanceManagement/acceptanceMange'
import { clonePage, getQueryObject, setDocTitle } from '@/utils'

import NextPage from '@/components/nextPerson/NextPage.vue'
import PrjAcceptInfo from './servicecodeDetailConfig/PrjAcceptInfo'
import BackPage from '@/components/nextPerson/BackPage.vue'
import TPageBtn from '@/components/basic/TPageBtn.vue'
import store from '@/store'
import JnPrjDetail from '@/components/jn/JnPrjDetail.vue'
import JnSiteDetail from '@/components/jn/JnSiteDetail.vue'
import JnProprietaryDetail from '@/components/jn/JnProprietaryDetail.vue'
import JnTaskDetail from '@/components/jn/JnTaskDetail.vue'
import ZrAttachmetl from '@/components/zr/ZrAttachmetl.vue'
const pageTitle = {
  'F4': '资源录入',
  'F5': '资源确认',
  'F10': '验收申请',
  'F11': '验收审核',
  'F91': '初验申请',
  'F92': '初验审核',
  'F93': '终验申请',
  'F94': '终验审核'
}
export default {
  name: 'AcceptMangeDetail',
  components: {
    JnPrjDetail,
    JnSiteDetail,
    JnProprietaryDetail,
    JnTaskDetail,
    ZrAttachmetl,
    TPageBtn,
    BackPage,
    PrjAcceptInfo,
    NextPage
  },
  data() {
    return {
      hasHeader: false,
      type: '',
      btnList: [],
      isPrjAcceptInfo: false,
      prjDetail: {
        prjId: '',
        btnType: '',
        pageType: '',
        accType: ''
      },
      prjId: '',
      activeNames: [],
      workItemId: '',
      fileObj: {
        nodeId: '',
        prjStage: '',
        prjType: '',
        buildModes: 1,
        towerType: 0,
        roomType: 0,
        isChange: 1,
        operateType: 1,
        btnConfig: 'B'
      },
      nextDialog: {
        nextPageVisible: false,
        activityInstID: '',
        processInstID: '',
        activityDefID: '',
        processDefName: '',
        activityInstName: ''
      },
      backDialog: {
        backPageVisible: false,
        backRoute: '1'
      },
      affirm: {
        dialogVisible: false,
        dialogVisible1: false,
        message: '请确认是否还有未申领的物资与未验工计价的服务？',
        type: 1
      },
      processInstId: ''
    }
  },
  async created() {
    // 附件最开始   公共最后,,其他校验再中间
    // 自主,1.附件必传 2,公共
    // 除了自主,其他都有终验,终验审核(F94)会有二次校验,(二次校验再公共校验之前)
    // type 0:我的待办跳转，1:综合查询跳转
    this.hasHeader = window.top === window
    const { workItemId = '', prjId = '', type, processInstId = '' } = getQueryObject()
    this.type = type
    this.processInstId = processInstId
    this.workItemId = workItemId
    this.prjId = prjId
    this.prjDetail.prjId = prjId
    await this.getPrjDetail()
  },
  methods: {
    // 非字自研项目 初验终验
    async inspectionCheck(workItem) {
      if (['F91', 'F93'].includes(workItem?.bizObject?.bizState)) {
        const params = {
          docType: 'TP01',
          prjStage: 'F',
          prjNode: workItem?.bizObject?.nodeCode,
          prjId: workItem?.bizObject?.prjId
        }
        await nonSelfResearchAcceptance(params)
      }
    },
    handleBtn(methodName) {
      this[methodName]()
    },
    // 关闭
    close() {
      clonePage()
    },
    // 回退
    doBack() {
      this.backDialog.backRoute = '1'
      this.backDialog.backPageVisible = true
    },
    async getPrjDetail() {
      if (this.workItemId) {
        const workItem = await getWFWorkItemApi(this.workItemId)
        console.log('流程信息', workItem)
        this.prjDetail.btnType = workItem.data?.bizObject?.bizState
        this.fileObj.prjStage = workItem.data?.bizObject?.wfStage
        this.fileObj.nodeId = workItem.data?.activityDefID
        this.nextDialog.activityInstID = workItem.data?.activityInstID
        this.nextDialog.processInstID = workItem.data?.processInstID
        this.nextDialog.activityDefID = workItem.data?.activityDefID
        this.nextDialog.processDefName = workItem.data?.processInstName
        this.nextDialog.activityInstName = workItem.data?.activityInstName
        this.btnList = JSON.parse(workItem.data?.bizObject?.buttonConfig) || []

        this.processInstId = workItem.data?.processInstID
        this.prjId = workItem.data?.bizObject?.prjId
        this.prjDetail.prjId = workItem.data?.bizObject?.prjId
        this.inspectionCheck(workItem.data)
        // store.commit('settings/setPageTitle', this.prjDetail.btnType)
        setDocTitle(pageTitle[this.prjDetail.btnType])
        store.commit('settings/setPageTitle', `${workItem.data?.processInstName}-验收-${pageTitle[this.prjDetail.btnType]}`)
      }
      const res = await getPrjDetailApi(this.prjId)
      console.log('基本信息', res)
      this.prjDetail.pageType = +res.data?.SECONDARYTYPE
      this.fileObj.prjType = res.data?.PRJTYPE
      this.fileObj.buildModes = res.data?.BUILDMODES
      this.prjDetail.accType = +res.data?.ACCTYPE
      // 仅终验的终验申请,取消回退按钮
      if (this.prjDetail.accType === 2 && this.prjDetail.btnType === 'F93') {
        this.btnList = this.btnList.filter(item => item.method !== 'doBack')
      }
      this.$nextTick(() => {
        this.isPrjAcceptInfo = true
      })
    },
    messageList(messageList) {
      if (messageList?.length > 0) {
        const message = messageList.shift()
        this.$alert(message, '提示', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          callback: action => {
            this.messageList(messageList)
          }
        })
      }
    },
    async checkMaterialServiceAmount() {
      const res = await checkMaterialServiceAmountApi(this.prjId) //
      if (+res.code !== 200) {
        return
      }
      if (res.data?.length) {
        this.messageList(res.data)
      } else {
        return true
      }
      console.log(res)
    },
    // 修复阻断
   async optimizeNewOne(){
     if (this.prjDetail.pageType === 14) {
       const data = await this.checkMaterialServiceAmount()
       if (!data) {
         return Promise.reject()
       }
     }
   },
   async optimizeNewTwo(){
     const res = await projectVisaVerificationApi(this.prjId)
     if (+res.code !== 200) {
       return Promise.reject()
     }
     return res
   },
    optimizeNewThree(res){
    return +res.code === 200 && res.data
   },
   async optimizeNewFour(){
     if (this.affirm.type === 3) {
       const res = await inspectionValuationPushApi(this.prjId)
       if (+res.code === 200) {
         this.nextEnd()
       }
     }
   },
   async optimizeNewFive(res){
    if(+res.code!==200){
      return Promise.reject()
    }
   },
    // 终验审核阶段需要二次确认
    async handleAffirm() {
      this.affirm.dialogVisible = false
      this.affirm.dialogVisible1 = false
      // 只有终验审核且项目类型是工程建设才有这弹框接口
      // 四个弹框中断流程,依次提示,二次确认
      // 200且data空,校验通过,其他都是失败,200且data有值依次弹框提示data数据<List<String>>
      if (this.affirm.type === 1) {
        await this.optimizeNewOne()
        const _res= await this.optimizeNewTwo()
        // if (this.prjDetail.pageType === 14) {
        //   const data = await this.checkMaterialServiceAmount()
        //   if (!data) {
        //     return
        //   }
        // }
        // const res = await projectVisaVerificationApi(this.prjId)
        // if (+res.code !== 200) {
        //   return
        // }
        this.affirm.type = 2
        if (this.optimizeNewThree(_res)) {
          this.affirm.message = _res.data
          this.affirm.dialogVisible = true
          return
        } else {
          return await this.handleAffirm()
        }
      }
      if (this.affirm.type === 2) {
        const res = await getNotPushedDetailCodeApi(this.prjId)
        this.affirm.type = 3
        await this.optimizeNewFive(res)
        if (res.data) {
          this.affirm.message = res.data
          //   `当前项目下还有服务验工计价未推送商合交易，请确认是否推送（点击“确定”推送）?
          // 如不需要推送请到“项目操作->采购操作->验工计价”功能中删除未推送的验工计价。
          // 注意：以下服务验工计价推送后需要重新确认站址服务绑定关系与服务配置明细！`
          // TODO 展示data标签
          this.affirm.dialogVisible = true
          return
        } else {
          return await this.handleAffirm()
        }
      }
      await this.optimizeNewFour()
    },
    // 展示下一步
    async doNext() {
      const dialogRes = this.$refs['prjAcceptInfo'].submit()
      if (!dialogRes?.success) {
        this.$message.warning(dialogRes?.message)
        return
      }
      const timeRes = await updateItAcceptTime(dialogRes.data)
      if (+timeRes.code !== 200) {
        return
      }
      const params = {
        prjId: this.prjId,
        nodeId: this.nextDialog.activityDefID, // 节点ID
        nodeName: this.nextDialog.activityInstName, // 节点名称
        commonCheck: [1, 2, 3], // 1.在途,2.必传附件,3.电子签章
        eventType: '1'
      }
      const res = await checkCommonVerificationApi(params)
      if (+res.code !== 200) {
        return
      } // this.$message.error(res.message)
      if (this.prjDetail.btnType === 'F94') {
        this.affirm.type = 1
        this.affirm.message = '请确认是否还有未申领的物资与未验工计价的服务？'
        this.affirm.dialogVisible1 = true
      } else {
        this.nextEnd()
      }
    },
    async nextEnd() {
      const params = {
        secondaryType: this.prjDetail.pageType,
        nodeState: this.prjDetail.btnType,
        prjId: this.prjId,
        nodeId: this.nextDialog.activityDefID,
        justFinalAccept: +this.prjDetail.accType === 2 // 是否仅终验,
      }
      const res = await itAcceptDoNextVerificationApi(params)
      if (res.code === '0033') {
        // 展示回退页面
        this.backDialog.backRoute = 'start'
        this.backDialog.backPageVisible = true
        return
      }
      if (+res.code !== 200) {
        return
      } // this.$message.error(res.message)
      // 展示君南弹框
      this.nextDialog.nextPageVisible = true
    },
    backPageRes(data) {
      const params = {
        'workItemId': this.workItemId,
        'opinion': data.opinion,
        'nextActDefId': data.nodeId, // 暂定
        'detailId': data.empId,
        'prjId': this.prjId,
        'activityDefId': this.nextDialog.activityDefID
      }
      backActivityApi(params).then(res => {
        if (+res.code === 200) {
          this.close()
        }
      })
    },
    // 确认下一步
    async nextPageRes(data) {
      const params = {
        'prjId': this.prjId,
        'workItemId': this.workItemId,
        'userIds': data.empId,
        'route': '1', // 下一步页面
        'wfXpath': [], // 暂时不传
        'opinion': data.opinion,
        'nextSceneId': data.nextSceneId, // 先不传
        'nodeId': data.nodeId,
        'detailId': data.detailId, // 先不传
        'route1': '1', // 决算页面
        'activityDefId': data.actDefId, // 当前节点
        'finish': data.finish, // 当前节点
        'templateId': data.nTemplateId
      }
      doNextFLowApi(params).then(res => {
        if (+res.code === 200) {
          this.close()
        }
      })
      console.log('下一步', data)
    },
    // 保存IT信息化项目验收时间
    save() {
      const res = this.$refs['prjAcceptInfo'].submit()
      if (res.success) {
        updateItAcceptTime(res.data).then(_res => {
          if (+_res.code === 200) {
            this.$message.success('保存成功')
          }
        })
      } else {
        this.$message.warning(res.message)
      }
    }
  }

}
</script>

<style>
.el-message-box {
  width: 500px;
}

.el-collapse-item {
  box-shadow: 0px 0px 6px 0px rgba(191, 192, 192, 0.52);
  /* 调整各个item之间的距离为20px */
  /* border: 1px; */
}

.el-collapse-item__wrap {
  padding: 0 20px;
  /* 为el-collapse-item的内容添加20像素的padding */
}

.el-collapse-item__header {
  padding-left: 20px;
  font-size: 14px;
  color: #333333;
  letter-spacing: 0;
  font-weight: 600;
}

.item_icon {
  width: 6px;
  background: rgb(235, 75, 75);
  height: 15px;
  margin-right: 10px;
  border-radius: 10px
}

.content-box {
  width: 100%;
  border-radius: 3px;
  font-size: 12px;
  font-weight: 400;
  line-height: 25px;
}
</style>
